package com.gisuni.sddc.platformManager.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.nutz.log.Logs;
import org.esrichina.gistech.config.Config;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.GET;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;

import com.gisuni.sddc.platformManager.model.Attachment;
import com.gisuni.sddc.platformManager.model.Response;
import com.gisuni.sddc.platformManager.model.ReturnObject;
import com.gisuni.sddc.platformManager.service.AttachmentService;
import com.gisuni.sddc.service.LoginService;


@IocBean(singleton=false)
@At("/client/backgroundManagement/AttachmentController")
public class AttachmentController {
//	private Log log=Logs.getLog(AttachmentController.class);
	private  Log log = Logs.getLog(AttachmentController.class);
	
	@Inject
	private  AttachmentService  attachmentService;
	
	static Config config=Config.getInstance();
	
	@At("/upload/")
	@POST
	@Ok("raw")
	public String uploadAttachment(HttpServletRequest request,HttpServletResponse response) throws IOException{
		ReturnObject ro=new ReturnObject();
		request.setCharacterEncoding("utf-8");
		DiskFileItemFactory factory =new DiskFileItemFactory();
		File file;
		String filepath="";
		String fileName="";
		String downFlag="";
		String ownerType="";
		String userId="";
		String ownerId="";
		String fileType="";
		String fileAbsName=UUID.randomUUID().toString();
		if(config!=null && config.getUploadfileconfig()!=null){
			filepath = config.getUploadfileconfig().getFileForMessPath();
			factory.setSizeThreshold( config.getUploadfileconfig().getMaxMemSize());
			factory.setRepository( new File( filepath + "tmp" ));
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setSizeMax(config.getUploadfileconfig().getMaxFileSize());
			try {
				List<?> fileItems = upload.parseRequest(request);
				for(int i=0;i<fileItems.size();i++){
					FileItem ft=(FileItem) fileItems.get(i);
					if(ft.isFormField()){
						String a = ft.getFieldName();
						if(a.equals("ownerType")){
							ownerType=new String(ft.get(),"utf-8");
						}else if(a.equals("userId")){
							userId=new String(ft.get(),"utf-8");
						}else if(a.equals("ownerId")){
							ownerId=new String(ft.get(),"utf-8");
						}else if(a.equals("type")){
							fileType=new String(ft.get(),"utf-8");
						}else if(a.equals("downFlag")){
							downFlag=new String(ft.get(),"utf-8");
						}else if(a.equals("fileName")){
							fileName=new String(ft.get(),"utf-8");
							fileName=java.net.URLDecoder.decode(fileName,"utf-8");
							
						}
					}
				}
				Iterator<?> i = fileItems.iterator();
				while(i.hasNext()){
					FileItem fi = (FileItem)i.next();
					if(!fi.isFormField()){
						file = new File( filepath + fileAbsName+fileName.substring(fileName.lastIndexOf(".")));
						fi.write(file);
					}
				}
				ro = new ReturnObject("ok","操作成功!",null,null);
			} catch (Exception e) {
				ro = new ReturnObject("fail","图片上传出错!",null,"upload file fail");
				log.error("upload file fail.  " + e);
				System.out.println("upload file fail.  " + e);
			}
		}else{
			//配置参数错误
			ro = new ReturnObject("error","图片上传出错!",null,"upload file fail");
			log.error("配置参数不正确!");
		}
		try{
			String attachMentId=UUID.randomUUID().toString();
			Attachment attachment=new Attachment();
			attachment.setId(attachMentId);
			attachment.setFileName(fileName);
			log.debug("取到文件名称为:"+fileName);
			attachment.setFilePath(filepath + fileAbsName+fileName.substring(fileName.lastIndexOf(".")));
			attachment.setOwnerType(ownerType);
			attachment.setOwner_id(ownerId);
			attachment.setUserId(userId);
			attachment.setFileType(fileType);
			attachment.setFlag(downFlag);
			attachmentService.addAttachment(attachment);	
			 ro = new ReturnObject("ok","操作成功!",null,null);
		}catch(Exception e){
			ro = new ReturnObject("error","内部错误!",null,"inner mistake");
			log.info(e);
		}
		return Json.toJson(ro,new JsonFormat()).replaceAll(":null,", ":\"\",");
	};
	@At("/getAttachByPath/")
	@GET
	@Ok("raw")
	public Object getAttachByPath(HttpServletResponse response,@Param("path")String filePath) throws IOException{
		try{
			File f = new File(filePath);
			if (!f.exists()) {
			      response.sendError(404, "File not found!");
			      return null;
			    }
		    BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
		    byte[] buf = new byte[1024];
		    int len = 0;
		    response.reset(); // 非常重要
		    URL u = new URL("file:///" + filePath);
		    response.setContentType(u.openConnection().getContentType());
		    response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
		     // 文件名应该编码成UTF-8
		    OutputStream out = response.getOutputStream();
		    while ((len = br.read(buf)) > 0)
		    out.write(buf, 0, len);
		    br.close();
		    out.flush();
		    out.close();
		    return out;
		}catch(Exception e){
			log.error(e);
			return null;
		}
	};
	@At("/downAttachByPath/")
	@GET
	@POST
	@Ok("raw")
	public HttpServletResponse download(@Param("path")String path,@Param("name")String name, HttpServletRequest request,HttpServletResponse response) {
		try {
            File file = new File(path);
            // 取得文件名。
            String filename = name;

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
//          response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(),"utf-8"));
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/x-msdownload");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    };
    @At("/deleteAttachmentById/")
    @POST
    @GET
    @Ok("json")
    public Object deleteAttachmentById(@Param("path")String path,@Param("id")String id){
    	Response res=new Response();
    	res.setSuccess(false);
    	try{
       	    boolean msg= attachmentService.deleteAttachmentById(id);
       	    boolean fileDeleteFlag=false;
       	    File file=new File(path);
       	    if(file.exists()){
       	    	if(file.delete()){
       	    		fileDeleteFlag=true;
       	    	}else{
       	    		fileDeleteFlag=false;
       	    	}
       	    }
       	 if(msg&&fileDeleteFlag==true){
       		 res.setSuccess(true);
       		 res.setMsg("删除成功");
       	 }else{
       		 res.setMsg("文件已不存在");
       	 }
       	}catch(Exception e){
       		log.error(e);
       		res.setMsg("操作失败");
       	}
   		return res;
    	
    }
    @At("/updateAttachmentDownStatusById/")
    @POST
    @GET
    @Ok("json")
    public Object updateAttachmentDownStatusById(@Param("id")String id,@Param("status") String status){
    	Response res=new Response();
    	res.setSuccess(false);
    	try{
    		 boolean msg= attachmentService.updateAttachmentDownStatusById(id,status);
    		 if(msg==true){
    			 res.setMsg("修改成功"); 
    			 res.setSuccess(true);
    		 }
    	}catch(Exception e){
    		log.error(e);
       		res.setMsg("修改失败");
    	}
    	return res;
    }
}
